package bar.dark.lee.manager.money;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import bar.dark.lee.BDConstents;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.common.EditTextInputFilter;
import bar.dark.lee.manager.card.CheckCardActivity;
import bar.dark.lee.manager.card.CreditCardActivity;
import bar.dark.lee.widget.WidgetGetSqlQuery;

public class BankBookUpdateActivity extends SuperActivity
{
	public static final String LINK_CARD = "link_card";
	public static final String CARD_ID = "card_id";
	
	private boolean checkCardFlag = false;
	private boolean creditCardFlag = false;
	
	private DBSQLite sql;
	
	private RadioButton radioButton1;
	private RadioButton radioButton2;
	
	private EditText nameEditText;
	private EditText moneyEditText;
	private EditText orderEditText;
	
	private Button minusButton;
	
	private Button deleteButton; 
	private Button updateButton;
	
	private BankbookData data;
	
	private int addflag = -1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		sql = DBSQLite.getInstance(this);
		
		setContentView(R.layout.bankbook_update);
		
		setGoneTipButton();
		
		setTitle("통장 수정");
		
		setFindView();
		setOnClickListener();
		setData();
	}

	private void setFindView()
	{
		radioButton1 = (RadioButton) findViewById(R.id.bankBookUpdateRadio1);
		radioButton2 = (RadioButton) findViewById(R.id.bankBookUpdateRadio2);
		
		nameEditText = (EditText) findViewById(R.id.bankbookUpdateName);
		moneyEditText = (EditText) findViewById(R.id.bankbookUpdateMoney);
		EditTextInputFilter.filteringMoneyEditText(moneyEditText);
		orderEditText = (EditText) findViewById(R.id.bankbookUpdateOrder);
		
		minusButton = (Button) findViewById(R.id.bankBookUpdateMinusButton);
		
		deleteButton = (Button) findViewById(R.id.bankBookDeleteButton);
		updateButton = (Button) findViewById(R.id.bankBookUpdateButton);
	}

	private void setOnClickListener()
	{
		minusButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				moneyEditText.setText("-");
				
				try {
					moneyEditText.setSelection(
							BDUtil.getCommaDel(moneyEditText.getText().toString()).length());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		
		deleteButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				setDeleteData();
			}
		});
		
		updateButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (nameEditText.getText().equals("") || nameEditText.getText().length() < 1)
				{
					BDUtil.showDialog(superContext, "확인", "통장 이름을 입력해주세요.");
					return;
				}
				
				if (orderEditText.getText().equals("") || orderEditText.getText().length() < 1
						|| Integer.parseInt(orderEditText.getText().toString()) < 1 || Integer.parseInt(orderEditText.getText().toString()) > 999 )
				{
					BDUtil.showDialog(superContext, "확인", "표시순위를 제대로 입력해주세요.(1~999)");
					return;
				}
				
				if (BDUtil.getCommaDel(moneyEditText.getText().toString()).equals("") 
						|| BDUtil.getCommaDel(moneyEditText.getText().toString()).equals("-") 
						|| BDUtil.getCommaDel(moneyEditText.getText().toString()).length() < 1)
				{
					BDUtil.showDialog(superContext, "확인", "금액을 제대로 입력해주세요.");
					return;
				}
				
				boolean nameOverlap = BDUtil.getOverlapCheck(sql, superContext, 
						"SELECT name FROM bankbook WHERE name = '" + 
								BDUtil.getApostrophe(nameEditText.getText().toString()) + "';");
				
				if (nameOverlap)
				{
					if (!nameEditText.getText().toString().equals(data.getName()))
					{
						BDUtil.showDialog(superContext, "확인", "동일한 통장 이름이 존재 합니다.");
						nameEditText.setText("");
						return;
					}
				}
				
				new ShowDialog().execute(BDUtil.asyncFlag, 2);
			}
		});
	}

	private void setData()
	{
		Intent intent = getIntent();
		data = intent.getParcelableExtra(BankMoneyActivitiy.BANKBOOK_DATA);
		
		nameEditText.setText(data.getName());
		moneyEditText.setText(data.getMoney());
		
		if (data.getOrder().equals("0"))
		{
			orderEditText.setText("999");
		}
		else
		{
			orderEditText.setText(data.getOrder());
		}
		
		addflag = -1;
		
		sql.selectMapTile(this, "SELECT addflag FROM bankbook_detail " +
				"WHERE linkid = " + data.getId() + ";", 
				new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int addflagIdx = c.getColumnIndex("addflag");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					addflag = c.getInt(addflagIdx);
					c.moveToNext();
				}
			}
		});
		
		if (addflag == 1)
		{
			radioButton2.setChecked(true);
		}
		else
		{
			radioButton1.setChecked(true);
		}
	}

	private void setDeleteData()
	{
		boolean checkFlag = getLinkCheckCard(data);
		
		boolean creditFlag = getLinkCreditCard(data);
		
		AlertDialog.Builder dialog = new AlertDialog.Builder(this);
		dialog.setTitle("경고");
		dialog.setIcon(android.R.drawable.ic_dialog_info);
		dialog.setMessage("연결된 카드를 변경하거나 삭제해 주세요. 통장이 삭제 될 경우 연결된 내역은 수정 삭제가 불가능합니다.");
		
		DialogInterface.OnClickListener onClickPositive = new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				Intent intent = new Intent(superContext, CheckCardActivity.class);
				intent.putExtra(LINK_CARD, true);
				intent.putExtra(CARD_ID, data.getId());
				startActivity(intent);
			}
		};
		
		DialogInterface.OnClickListener onClickNeutral = new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				Intent intent = new Intent(superContext, CreditCardActivity.class);
				intent.putExtra(LINK_CARD, true);
				intent.putExtra(CARD_ID, data.getId());
				startActivity(intent);
			}
		};
		
		if (checkFlag && creditFlag)
		{
			dialog.setPositiveButton("체크", onClickPositive);
			dialog.setNeutralButton("신용", onClickNeutral);
		}
		else if (checkFlag)
		{
			dialog.setPositiveButton("체크", onClickPositive);
		}
		else if (creditFlag)
		{
			dialog.setNeutralButton("신용", onClickNeutral);
		}
		
		dialog.setNegativeButton("취소", new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
			}
		});
		
		if (checkFlag || creditFlag)
		{
			dialog.show();
			return;
		}
		else
		{
			new ShowDialog().execute(BDUtil.asyncFlag, 1);
			return;
		}
	}
	
	/**
	 * 통장에 연결된 체크카드가 있는지 가져온다.
	 * @param data
	 * @return
	 */
	private boolean getLinkCheckCard(BankbookData data)
	{
		checkCardFlag = false;
		
		sql.selectMapTile(this, "SELECT banklink FROM check_card WHERE banklink = "
				+ data.getId() + ";" , new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				if (c.getCount() > 0)
				{
					checkCardFlag = true;
				}
				else
				{
					checkCardFlag  = false;
				}
			}
		
		});
		return checkCardFlag;
	}
	
	/**
	 * 통장에 연결된 신용카드가 있는지 가져온다.
	 * @param data
	 * @return
	 */
	private boolean getLinkCreditCard(BankbookData data)
	{
		creditCardFlag = false;
		
		sql.selectMapTile(this, "SELECT banklink FROM credit_card WHERE banklink = "
				+ data.getId() + ";", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				if (c.getCount() > 0)
				{
					creditCardFlag = true;
				}
				else
				{
					creditCardFlag  = false;
				}
			}
		});
		
		return creditCardFlag;
	}
	
	private void setBankBookDeleteData()
	{
		String [] whereArgs = new String[]{data.getId()};
		sql.delete(this, "bankbook", "id = ?", whereArgs);
		
		// 통장 자동화 테이블도 같이 삭제 됩니다.
		sql.selectMapTile(this, "SELECT id FROM auto_bank WHERE moneykind = '"
				+ BDUtil.getApostrophe(data.getName()) + "' and kind = 1;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				ArrayList<String> ids = new ArrayList<String>();
				
				int idIdx = c.getColumnIndex("id");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					ids.add(c.getInt(idIdx) + "");
					c.moveToNext();
				}
				
				for (int j = 0; j < ids.size(); j++)
				{
					String id = ids.get(j);
					String [] whereArgs = new String[]{id};
					sql.delete(superContext, "auto_bank", "id = ?", whereArgs);
				}
			}
		});
		
		// 내통장이체 자동화 테이블도 같이 삭제 됩니다.
		sql.selectMapTile(this, "SELECT id FROM auto_mybank WHERE inkind = '"
				+ BDUtil.getApostrophe(data.getName()) + "' or outkind = '" 
				+ BDUtil.getApostrophe(data.getName()) + "' and kind = 1;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				ArrayList<String> ids = new ArrayList<String>();
				
				int idIdx = c.getColumnIndex("id");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					ids.add(c.getInt(idIdx) + "");
					c.moveToNext();
				}
				
				for (int j = 0; j < ids.size(); j++)
				{
					String id = ids.get(j);
					String [] whereArgs = new String[]{id};
					sql.delete(superContext, "auto_mybank", "id = ?", whereArgs);
				}
			}
		});
		
		// 세부통장 테이블에서도 삭제한다
		String [] whereArgs2 = new String[]{data.getId()};
		sql.delete(this, "bankbook_detail", "linkid = ?", whereArgs2);
		
		// 통장에 연결된 내역들을 수정이나 삭제 못하게 막는다.
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("deleteyn", "1");
		String [] whereArgs1 = new String[]{
				BDConstents.BANK_TYPE, data.getName()};
		
		sql.update(this, 
				"in_out", map, "type = ? and moneykind = ?", whereArgs1);
		
		sql.update(this, 
				"in_out", map, "linktype = ? and moneykind = ?", whereArgs1);
		
		// 자산이 삭제 되면 메인 화면 셋팅 값도 같이 삭제 한다.
		WidgetGetSqlQuery widgetQuery = new WidgetGetSqlQuery(superContext);
		widgetQuery.setManagerDelete(data.getName(), WidgetGetSqlQuery.BANKBOOK);
	}
	
	private void setBankMoneyUpdateData()
	{
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("money", BDUtil.getCommaDel(moneyEditText.getText().toString()));
		map.put("name", nameEditText.getText().toString());
		String [] whereArgs = new String[]{data.getId()};
		sql.update(this, "bankbook", map, "id = ?", whereArgs);
		
		// 통장 자동화 테이블도 같이 수정 됩니다.
		sql.selectMapTile(this, "SELECT id FROM auto_bank WHERE moneykind = '"
				+ BDUtil.getApostrophe(data.getName()) + "' and kind = 1;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				ArrayList<String> ids = new ArrayList<String>();
				
				int idIdx = c.getColumnIndex("id");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					ids.add(c.getInt(idIdx) + "");
					c.moveToNext();
				}
				
				for (int j = 0; j < ids.size(); j++)
				{
					String id = ids.get(j);
					
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("moneykind", nameEditText.getText().toString());
					
					String [] whereArgs = new String[]{id};
					sql.update(superContext, "auto_bank", map, "id = ?", whereArgs);
				}
			}
		});
		
		// 내통장이체 자동화 테이블도 같이 수정 됩니다.
		sql.selectMapTile(this, "SELECT id FROM auto_mybank WHERE outkind = '"
				+ BDUtil.getApostrophe(data.getName()) + "' and kind = 1;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				ArrayList<String> ids = new ArrayList<String>();
				
				int idIdx = c.getColumnIndex("id");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					ids.add(c.getInt(idIdx) + "");
					c.moveToNext();
				}
				
				for (int j = 0; j < ids.size(); j++)
				{
					String id = ids.get(j);
					
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("outkind", nameEditText.getText().toString());
					
					String [] whereArgs = new String[]{id};
					sql.update(superContext, "auto_mybank", map, "id = ?", whereArgs);
				}
			}
		});
		
		sql.selectMapTile(this, "SELECT id FROM auto_mybank WHERE inkind = '"
				+ BDUtil.getApostrophe(data.getName()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				ArrayList<String> ids = new ArrayList<String>();
				
				int idIdx = c.getColumnIndex("id");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					ids.add(c.getInt(idIdx) + "");
					c.moveToNext();
				}
				
				for (int j = 0; j < ids.size(); j++)
				{
					String id = ids.get(j);
					
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("inkind", nameEditText.getText().toString());
					
					String [] whereArgs = new String[]{id};
					sql.update(superContext, "auto_mybank", map, "id = ?", whereArgs);
				}
			}
		});
		
//		if (addflag == -1)
//		{
//			map.clear();
//			map.put("name", nameEditText.getText().toString());
//			map.put("linkid", data.getId());
//			map.put("count", orderEditText.getText().toString());
//			
//			if (radioButton1.isChecked())
//			{
//				map.put("addflag", "0");
//			}
//			else
//			{
//				map.put("addflag", "1");
//			}
//			
//			// 세부 통장 테이블에 데이터를 셋팅한디.
//			sql.insert(superContext, map, "bankbook_detail");
//		}
//		else
//		{
			map.clear();
			map.put("name", nameEditText.getText().toString());
			map.put("count", orderEditText.getText().toString());
			
			if (radioButton1.isChecked())
			{
				map.put("addflag", "0");
			}
			else
			{
				map.put("addflag", "1");
			}
			
			String [] whereArgs2 = new String[]{data.getId()};
			
			// 세부 통장 테이블에 데이터를 수정한다.
			sql.update(superContext, "bankbook_detail", map, "linkid = ?", whereArgs2);
//		}
			
		// 자산이 수정 되면 메인 화면 셋팅 값도 같이 수정 한다.
		WidgetGetSqlQuery widgetQuery = new WidgetGetSqlQuery(superContext);
		widgetQuery.setManagerUpdate(data.getName(), 
				nameEditText.getText().toString(), WidgetGetSqlQuery.BANKBOOK);
	}
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (BDUtil.btnEnable)
			{
				BDUtil.btnEnable = false;
				BDUtil.asyncFlag = -1;
				
				dialog = new ProgressDialog(superContext);
				dialog.setCancelable(false);
				dialog.setMessage("Loading...");
				dialog.show();
			}
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			
			if (arg0[0] == 0) 
			{
				if (arg0[1] == 1) 
				{
					try
					{
						sql.beginTansaction(superContext);
						
						setBankBookDeleteData();
						
						sql.setTransactionSuccessful();
					} catch (Exception e)
					{
						return -1;
					} finally {
						try 
						{
							sql.endTransaction(superContext);
						} catch (Exception e) 
						{
							return -1;
						}
					}
					
					return arg0[1];
				}
				else if (arg0[1] == 2)
				{
					try
					{
						sql.beginTansaction(superContext);
						
						setBankMoneyUpdateData();
						
						sql.setTransactionSuccessful();
					} catch (Exception e)
					{
						return -1;
					} finally {
						try 
						{
							sql.endTransaction(superContext);
						} catch (Exception e) 
						{
							return -1;
						}
					}
					
					return arg0[1];
				}
				return arg0[0];
				
			} else 
				return arg0[0];
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
			if (dialog != null) {
				dialog.dismiss();
			}
			
			if (result == -1)
			{
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
				
				BDUtil.showDialog(superContext, "오류", "데이터 저장에 실패했습니다.");
			}
			else if (result == 1)
			{
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
				
				BDUtil.showDialogFinish(superContext, "삭제완료", "통장이 삭제 되었습니다.");
			}
			else if (result == 2)
			{
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
				
				BDUtil.showDialogFinish(superContext, "수정완료", "통장이 수정 되었습니다.");
			}
		}
	}
	
	@Override
	protected void tipButton()
	{
	}

}
